package com.singfan.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.singfan.common.SingFanException;

import java.io.IOException;

/**
 * JSON相关工具类
 * Author: HanSongHe
 * Date: 2015-05-28 10:20
 * Desc: 基于jackson封装的
 */
public class JsonUtil {
    /**
     * 将bean对象序列化成json字符串（bean对象是null时则为空字符）
     * @param beanObject bean对象
     * @return json字符串
     */
    public static String bean2Json(Object beanObject) {
        String result;
        if(beanObject != null){
            ObjectMapper mapper = new ObjectMapper();
            try {
                result = mapper.writeValueAsString(beanObject);
            }
            catch(JsonProcessingException e) {
                throw new SingFanException(String.format("JsonUtil.bean2Json() error: %s !", e.getMessage()), e);
            }
        }
        else{
            result = "";
        }
        return result;
    }

    /**
     * 将json字符串反序列化成bean对象（1.bean必须有默认的构造函数 2.当json为空字符串时返回null）
     * @param json json字符串
     * @param tClass bean对象的类型信息
     * @param <T>
     * @return bean对象
     */
    public static <T> T json2Bean(String json, Class<T> tClass){
        T result;

        if(StringUtil.isNullOrEmpty(json)){
            result = null;
        }
        else{
            ObjectMapper mapper = new ObjectMapper();
            try {
                result = mapper.readValue(json, tClass);
            }
            catch(IOException e) {
                throw new SingFanException(String.format("JsonUtil.json2Bean() error: %s !", e.getMessage()), e);
            }
        }

        return result;
    }
}
